import 'package:fast_cached_network_image/fast_cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_image_picker/repository/upload_repository.dart';
import 'package:flutter_image_picker/util/file_preview_helper.dart';
import 'package:flutter_image_picker/util/toast_util.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:jiffy/jiffy.dart';
import 'model/upload_history_result.dart';

/// 上传历史页面
class UploadHistoryPage extends StatefulWidget {
  const UploadHistoryPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return UploadHistoryPageState();
  }
}

class UploadHistoryPageState extends State<UploadHistoryPage> {
  /// 下拉刷新控制器
  final EasyRefreshController _refreshController = EasyRefreshController();

  /// 列表条目
  final List<Data> _itemList = [];

  /// 下拉刷新
  void _refresh() async {
    _getUploadHistoryList(() {
      _refreshController.finishRefresh(success: true);
    });
  }

  /// 加载更多
  void _loadMore() async {
    _getUploadHistoryList(() {
      _refreshController.finishLoad(noMore: false);
    });
  }

  /// 获取上传历史
  void _getUploadHistoryList(Function callback) {
    UploadRepository.getUploadHistoryList((result) {
      setState(() {
        _itemList.clear();
        _itemList.addAll(result.data ?? []);
      });
      callback();
    }, (msg, code) {
      ToastUtil.toast(msg);
      callback();
    });
  }

  /// 删除某条上传历史记录
  void _deleteUploadHistory(Data item, int index) {
    var id = item.id ?? "";
    if (id.isEmpty) {
      return;
    }
    UploadRepository.deleteUploadHistory(id, (model) {
      setState(() {
        ToastUtil.toast("删除成功");
        _itemList.removeAt(index);
      });
    }, (code, msg) {
      ToastUtil.toast("删除失败：$msg");
    });
  }

  @override
  void initState() {
    super.initState();
    _refresh();
  }

  /// 构建图标
  Widget _buildIconWidget(String url) {
    var width = 50.0;
    var height = 50.0;
    if (FilePreviewHelper.isImageFile(url)) {
      return FastCachedImage(
        width: width,
        height: height,
        url: url,
        fit: BoxFit.cover,
      );
    } else {
      return Container(
        width: width,
        height: height,
        color: Colors.grey,
        child: const Center(
          child: Text(
            "视频",
            style: TextStyle(
              color: Colors.white,
              fontSize: 13.0,
            ),
          ),
        ),
      );
    }
  }

  /// 处理条目点击
  void _handleOnTapItem(Data item) {
    var itemFileUrl = item.url ?? "";
    if (FilePreviewHelper.isImageFile(itemFileUrl)) {
      //跳转到图片预览页面
      FilePreviewHelper.goImageViewerPage(
        context,
        _itemList.map((item) => item.url ?? "").toList(),
        _itemList.indexOf(item),
      );
    } else {
      //跳转到视频预览页面
      FilePreviewHelper.goVideoViewerPage(context, itemFileUrl);
    }
  }

  /// 构建条目
  Widget _buildItem(Data item, int index) {
    return Slidable(
      key: ValueKey("$index"),
      direction: Axis.horizontal,
      endActionPane: ActionPane(
        motion: const ScrollMotion(),
        children: [
          SlidableAction(
            padding: const EdgeInsets.only(top: 10, bottom: 10),
            backgroundColor: Colors.red,
            foregroundColor: Colors.white,
            icon: Icons.delete,
            label: '删除',
            onPressed: (BuildContext context) {
              _deleteUploadHistory(_itemList[index], index);
            },
          ),
        ],
      ),
      child: GestureDetector(
        //点击空白位置，也响应事件，不设置的话，只有点击图片和文字时，才响应事件
        behavior: HitTestBehavior.opaque,
        onTap: () {
          _handleOnTapItem(item);
        },
        child: Padding(
          padding: const EdgeInsets.all(15.0),
          child: Row(
            children: [
              _buildIconWidget(item.url ?? ""),
              Container(
                margin: const EdgeInsets.only(left: 15.0),
                child: Padding(
                  padding: const EdgeInsets.symmetric(vertical: 5.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        item.fileName ?? "",
                        style: const TextStyle(fontSize: 13.0),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                      Container(
                        height: 5.0,
                      ),
                      Text(
                        item.createTime == null
                            ? ""
                            : Jiffy.parseFromDateTime(
                                    DateTime.fromMillisecondsSinceEpoch(
                                        int.parse(item.createTime!)))
                                .format(pattern: "yyyy-MM-dd HH:mm:ss"),
                        style:
                            const TextStyle(color: Colors.grey, fontSize: 12.0),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      )
                    ],
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
            onPressed: () {
              Navigator.pop(context, null);
            },
            icon: const Icon(Icons.arrow_back)),
        title: const Text("上传历史"),
      ),
      body: EasyRefresh(
        header: ClassicalHeader(
          refreshText: "下拉可以刷新",
          refreshReadyText: "松开立即刷新",
          refreshingText: "正在刷新数据中...",
          refreshedText: "刷新完成",
          infoText: "上次更新 %T",
        ),
        footer: ClassicalFooter(),
        controller: _refreshController,
        onRefresh: () async {
          _refresh();
        },
        onLoad: null,
        child: ListView.separated(
          itemCount: _itemList.length,
          //分割线
          separatorBuilder: (BuildContext context, int index) {
            return const Divider(
              height: 1,
              indent: 0,
              color: Color(0xFFDDDDDD),
            );
          },
          //条目
          itemBuilder: (context, index) {
            return _buildItem(_itemList[index], index);
          },
        ),
      ),
    );
  }
}
